package edu.ccut.saturn.studio.wfg.dialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.search.dialog.OneCompontentSearchDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.ExtendAttributeForLogicKeyLabelProvider;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.MyCellModifierExtendAttributeForLogicKey;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicParameterAddDialog;
import edu.ccut.saturn.studio.wfg.dialog.vocationallogicdialog.SaturnVocationalLogicParameterEditDialog;
import edu.ccut.saturn.studio.wfg.model.Shape;
import edu.ccut.saturn.studio.wfg.wfgmodel.ExtendAttributeForLogicKey;
import edu.ccut.saturn.studio.wfg.wfgmodel.LogicKeyAttribute;
import edu.ccut.saturn.studio.wfg.wfgmodel.SaturnAttribute;

public class CustomDefineParticipantDialog<T extends Shape> extends TitleAreaDialog {
	
	private T shape;
	
	private LogicKeyAttribute logicKeyAttribute;
	
	private ExtendAttributeForLogicKey extendAttributeForLogicKey;
	
	private List<SaturnAttribute> attributes;
	
	private TableViewer tableViewer;
	
	private Table table;
	
	private Text logicKeyText;
	
	private Label logicKeyLabel, browser;
	
	private Button addButton, deleteButton, editButton;

	private CellEditor[] cellEditor;
	
	public CustomDefineParticipantDialog(Shell parentShell, LogicKeyAttribute logicKeyAttribute, T shape) {
		super(parentShell);
		this.shape = shape;
		this.logicKeyAttribute = logicKeyAttribute;
		this.attributes = logicKeyAttribute.getAttributes();//logicKey本身还包括一个小型的List
	}
	
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(Messages.getString("CustomDefineParticipantDialog.0"));    //$NON-NLS-1$
		return contents;
	}
	
	protected Control createDialogArea(Composite parent) {
		
		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));
		
		Composite area = (Composite) super.createDialogArea(parent);
		final Composite composite = new Composite(area, SWT.NONE);
		
		final GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, false);
		composite.setLayoutData(gd_composite);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		composite.setLayout(gridLayout);

		logicKeyLabel = new Label(composite, SWT.NONE);
		final GridData gd_logicKeyLabel = new GridData();
		gd_logicKeyLabel.verticalIndent = 10;
		logicKeyLabel.setLayoutData(gd_logicKeyLabel);
		logicKeyLabel.setText("LogicKey");

		logicKeyText = new Text(composite, SWT.BORDER);
		final GridData gd_logicKeyText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_logicKeyText.verticalIndent = 10;
		logicKeyText.setLayoutData(gd_logicKeyText);
		
		browser = new Label(composite, SWT.BORDER);
		browser.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
//				try {
//					tempMap = shape.keyMapInProject();
//				} catch (Exception e1) {
//					e1.printStackTrace();
//				}
//				if(tempMap==null){
//					return;
//				}
//				
//				Set<String> s = tempMap.keySet();
//				String ss [] = SearchHelp.conversion(s);
//				ElementListSelectionDialog dialog1 = new ElementListSelectionDialog(
//						Display.getDefault().getShells()[0], new KeyLabelPrivoder());
//				dialog1.setTitle(Messages.getString("CustomDefineParticipantDialog.1"));    //$NON-NLS-1$
//				
//				dialog1.setElements(ss);
//				if(dialog1.open() == Window.OK){
//					if(attributes.size() > 0){
//						attributes.clear();
//					}
//					logicKeyText.setText((String) dialog1.getFirstResult());
//					// 得到了document，现在解析这段document
//					Document document = tempMap.get(logicKeyText.getText().trim());
//					NodeList nodelist = document.getDocumentElement().getElementsByTagName("start");
//					Node startNode = nodelist.item(0);
//					if(startNode!=null){
//						List<Node> parametersNodeList = new ArrayList<Node>();
//						NodeList paraList = startNode.getChildNodes();
//						for(int i = 0; i < paraList.getLength(); i++){
//							if("parameters".equals(paraList.item(i).getNodeName())){
//								NodeList pList = paraList.item(i).getChildNodes();
//								for(int j = 0; j < pList.getLength(); j++){
//									if("parameter".equals(pList.item(j).getNodeName())){
//										parametersNodeList.add(pList.item(j));
//									}
//								}
//							}
//						}
//						
//						for (Node n: parametersNodeList){
//							ExtendAttributeForLogicKey ea = new ExtendAttributeForLogicKey();
//							String strID = XmlModelUtil.getNodeAttributeValue(n, "id");
//							ea.setId(strID);
//							NodeList vk = n.getChildNodes();
//							for(int i = 0; i < vk.getLength(); i++){
//								if("value-key".equals(vk.item(i).getNodeName())){
//									String strValueKey = XmlModelUtil.getNodeElementValue(n, "value-key");
//									ea.setParameter(strValueKey);
//								}
//							}
//							attributes.add(ea);
//						}
//					}
//					tableViewer.setInput(attributes);
//				}
				OneCompontentSearchDialog searchDialog = new OneCompontentSearchDialog(
						Display.getDefault().getShells()[0],shape);
				
				if (searchDialog.open() == Window.OK) {
					logicKeyText.setText(((SearchResult)searchDialog.getFirstResult()).getKey());
					
					Document document = ((SearchResult)searchDialog.getFirstResult()).getDocument();
					NodeList nodelist = document.getDocumentElement().getElementsByTagName("start");
					Node startNode = nodelist.item(0);
					if(startNode!=null){
						List<Node> parametersNodeList = new ArrayList<Node>();
						NodeList paraList = startNode.getChildNodes();
						for(int i = 0; i < paraList.getLength(); i++){
							if("parameters".equals(paraList.item(i).getNodeName())){
								NodeList pList = paraList.item(i).getChildNodes();
								for(int j = 0; j < pList.getLength(); j++){
									if("parameter".equals(pList.item(j).getNodeName())){
										parametersNodeList.add(pList.item(j));
									}
								}
							}
						}
						
						for (Node n: parametersNodeList){
							ExtendAttributeForLogicKey ea = new ExtendAttributeForLogicKey();
							String strID = SaturnW3CUtil.getNodeAttributeValue(n, "id");
							ea.setId(strID);
							NodeList vk = n.getChildNodes();
							for(int i = 0; i < vk.getLength(); i++){
								if("value-key".equals(vk.item(i).getNodeName())){
									String strValueKey = SaturnW3CUtil.getChildNodeValue(n, "value-key");
									ea.setParameter(strValueKey);
								}
							}
							attributes.add(ea);
						}
					}
					tableViewer.setInput(attributes);
				}
				
			}
		});
		browser.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browser.setImage(Activator.getImage(Images.AMPLIFY_MINUS));  
			}
			public void mouseExit(final MouseEvent e) {
				browser.setImage(Activator.getImage(Images.AMPLIFY_PLUS));  
			}
		});
		final GridData gd_browser = new GridData(SWT.FILL, SWT.CENTER, false, false);
		gd_browser.verticalIndent = 7;
		gd_browser.horizontalIndent = 1;
		browser.setLayoutData(gd_browser);
		browser.setImage(Activator.getImage(Images.AMPLIFY_PLUS));  

		final Group logickeyGroup = new Group(area, SWT.NONE);
		logickeyGroup.setLayout(new FormLayout());
		logickeyGroup.setText("group");
		final GridData gd_logickeyGroup = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_logickeyGroup.verticalIndent = 10;
		gd_logickeyGroup.widthHint = 480;
		gd_logickeyGroup.heightHint = 185;
		logickeyGroup.setLayoutData(gd_logickeyGroup);

		tableViewer = new TableViewer(logickeyGroup, SWT.FULL_SELECTION | SWT.BORDER | SWT.MULTI);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.right = new FormAttachment(100, -85);
		fd_table.bottom = new FormAttachment(100,-5);
		fd_table.top = new FormAttachment(0, 5);
		fd_table.left = new FormAttachment(0, 5);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new ExtendAttributeForLogicKeyLabelProvider());
		
		tableViewer.setColumnProperties(new String[] { "id", "parameter"});
		cellEditor = new CellEditor[3];
		cellEditor[0] = null;
		cellEditor[1] = new TextCellEditor(tableViewer.getTable());

		tableViewer.setCellEditors(cellEditor);
		tableViewer.setCellModifier(new MyCellModifierExtendAttributeForLogicKey(tableViewer));

		final TableColumn newColumnTableColumn = new TableColumn(table, SWT.NONE);
		newColumnTableColumn.setWidth(100);
		newColumnTableColumn.setText("ID");

		final TableColumn tableColumn = new TableColumn(table, SWT.NONE);
		tableColumn.setWidth(270);
		tableColumn.setText("parameter");

		addButton = new Button(logickeyGroup, SWT.NONE);
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				openAddDialog();
			}
		});
		final FormData fd_button = new FormData();
		fd_button.top = new FormAttachment(table, 0, SWT.TOP);
		fd_button.left = new FormAttachment(100, -70);
		fd_button.right = new FormAttachment(100, -15);
		addButton.setLayoutData(fd_button);
		addButton.setText(SelectionCandidate.INSERT_BUTTON);

		editButton = new Button(logickeyGroup, SWT.NONE);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_EDIT_RECORD);
				} else {
					extendAttributeForLogicKey = (ExtendAttributeForLogicKey)selection.getFirstElement();
					openEditDialog(extendAttributeForLogicKey);
					tableViewer.refresh();
				}
			}
		});
		final FormData fd_button_4 = new FormData();
		fd_button_4.top = new FormAttachment(addButton, 10, SWT.BOTTOM);
		fd_button_4.right = new FormAttachment(addButton, 0, SWT.RIGHT);
		fd_button_4.left = new FormAttachment(addButton, 0, SWT.LEFT);
		editButton.setLayoutData(fd_button_4);
		editButton.setText(SelectionCandidate.EDIT_BUTTON);
		
		deleteButton = new Button(logickeyGroup, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
				extendAttributeForLogicKey = (ExtendAttributeForLogicKey)selection.getFirstElement();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null, SelectionCandidate.HINT, SelectionCandidate.CHOOSE_DELETE_RECORD);
				} else {
					List<SaturnAttribute> logicKeyParameterListForDelete = (List<SaturnAttribute>) tableViewer.getInput();
					logicKeyParameterListForDelete.remove(extendAttributeForLogicKey);
					reorder(logicKeyParameterListForDelete);
					tableViewer.setInput(logicKeyParameterListForDelete);
					
				}
			}
		});
		final FormData fd_button_1 = new FormData();
		fd_button_1.top = new FormAttachment(editButton, 10, SWT.BOTTOM);
		fd_button_1.left = new FormAttachment(addButton, 0, SWT.LEFT);
		fd_button_1.right = new FormAttachment(addButton, 0, SWT.RIGHT);
		deleteButton.setLayoutData(fd_button_1);
		deleteButton.setText(SelectionCandidate.DELETE_BUTTON);
		
		// logicKey不可以为空的判断
		if("".equals(logicKeyText.getText().trim())){
			setErrorMessage(Messages.getString("CustomDefineParticipantDialog.logicKeyISNotEmpty"));    //$NON-NLS-1$
		}
		logicKeyText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				if("".equals(logicKeyText.getText().trim())){
					setErrorMessage(Messages.getString("CustomDefineParticipantDialog.logicKeyISNotEmpty2"));    //$NON-NLS-1$
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				}else{
					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
				}
			}
		});
		
		return area;
	}
	
	@Override
	protected void buttonPressed(int buttonId) {
		if(buttonId == IDialogConstants.OK_ID){
			logicKeyAttribute.setKey(logicKeyText.getText().trim());
		}
		super.buttonPressed(buttonId);
	}
	
	private void openAddDialog(){
		SaturnVocationalLogicParameterAddDialog addDialog = new SaturnVocationalLogicParameterAddDialog(
				Display.getDefault().getShells()[0], attributes);
		if (addDialog.open() == IDialogConstants.OK_ID) {
			tableViewer.setInput(attributes);
		}
	}
	
	private void openEditDialog(ExtendAttributeForLogicKey extendAttributeForLogicKey){
		SaturnVocationalLogicParameterEditDialog editDialog = new SaturnVocationalLogicParameterEditDialog(
				Display.getDefault().getShells()[0], extendAttributeForLogicKey);
		editDialog.open();
	}
	
	private void reorder(List<SaturnAttribute> attributes){
		for (int i = 0; i < attributes.size(); i++) {
			ExtendAttributeForLogicKey extendAttributeForLogicKey = (ExtendAttributeForLogicKey)attributes.get(i);
			extendAttributeForLogicKey.setId(String.valueOf(i + 1));
		}
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}

	protected Point getInitialSize() {
		return new Point(480, 360);
	}
	
	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}
	
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		getButton(IDialogConstants.OK_ID).setEnabled(false);
	}
}
